package com.matrix.rpc.registry;

import com.matrix.rpc.client.RpcClient;
import org.apache.zookeeper.*;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

public class ServiceRegistry {

    private final String registerAddress;

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RpcClient.class);
    private CountDownLatch latch = new CountDownLatch(1);

    public ServiceRegistry(String registerAddress) {
        this.registerAddress = registerAddress;
    }


    public void register(String data) {
        if (data != null) {
            ZooKeeper zk = connectServer(registerAddress);
            if (zk != null) {
                createNode(zk, data);
            }
        }

    }

    private void createNode(ZooKeeper zk, String data) {
        try {
            byte[] bytes = data.getBytes();
            if (zk.exists(Constant.ZK_REGISTRY_PATH, null) == null) {
                zk.create(Constant.ZK_REGISTRY_PATH, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

            String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            LOGGER.debug("create zookeeper node " + path + "=>" +data);
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }

    public ZooKeeper connectServer(String registerAddress) {
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(registerAddress, Constant.ZK_ZOOKEEPER_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        return zk;
    }
}
